/**
 * Copyright (c) 2020-2024, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.leetcode;

/**
 * @author Xue Xue (xuexue1@huli.com)
 * @version 1.0
 * @since 2020/8/27
 */
public class Q563 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    private int sum = 0;

    public int findTilt(TreeNode root) {
        if (root.left == null && root.right == null) {
            return sum;
        }
        if (root.left == null) {
            return sum += root.val + findTilt(root.right);
        } else if (root.right == null) {
            return sum += root.val + findTilt(root.left);
        }
        return sum += Math.abs(root.left.val - root.right.val) + findTilt(root.left) + findTilt(root.right);

    }

    public static void main(String[] args) {
        Q563 q563 = new Q563();

        TreeNode a = q563.new TreeNode(2);
        TreeNode root = q563.new TreeNode(1);
        root.right = a;
        System.out.println(q563.findTilt(root));

    }
}
